<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="name">
              <el-input v-model="filters.name" clearable placeholder="小区名称"></el-input>
            </el-form-item>
            <el-form-item prop="streetIds">
              <Region :streetValues="filters.streetIds" @regionChange="handleItemChange" :isChangeOnSelect="true"> </Region>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button type="warning" plain icon="fa fa-plus" v-has="permissionChannel" @click="handleClickChannel()" size="mini"> 批量上传通道</el-button>
            <el-button type="warning" plain icon="fa fa-plus" v-has="permissionResident" @click="handleImportResident()" size="mini"> 批量导入住户</el-button>
            <!--            <el-button type="warning" v-has="permissionBatchPromote" plain icon="el-icon-s-opportunity" @click="handleBatchPromoteSet"   size="mini">批量推广设置</el-button>-->
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table
        ref="tableList"
        :data="dataList"
        :fit="true"
        highlight-current-row
        v-loading="listLoading"
        @selection-change="handleSelectChange"
        element-loading-text="数据加载中，请稍后..."
        empty-text="对不起，没有找到相关数据！"
      >
        <!-- @row-click="$refs.tableList.toggleRowSelection($event)" -->
        <el-table-column align="center" type="selection"></el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" label="小区名称" prop="villageName"> </el-table-column>
        <el-table-column align="center" label="小区地址" prop="address"> </el-table-column>
        <el-table-column align="center" width="200" label="创建人" prop="createUserName"> </el-table-column>
        <el-table-column align="center" width="200" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column align="center" width="200" label="修改人" prop="modifyUserName"> </el-table-column>
        <el-table-column align="center" width="200" label="修改时间" prop="modifyDate"> </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-button v-has="permissionStatisticsUser" @click="handleClickStatistics(scope.row)" size="mini">统计</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                <el-dropdown-item v-has="permissionPerfect" @click.native="handleClickPerfect(scope.row)">完善数据</el-dropdown-item>
                <el-dropdown-item v-has="permissionQrcode" @click.native="handleGetQrocde(scope.row)">生成二维码</el-dropdown-item>
                <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                <el-dropdown-item v-has="permissionChannel" @click.native="handleClickChannel(scope.row)">上传通道</el-dropdown-item>
                <!--                <el-dropdown-item v-has="permissionPromote"  @click.native="handlePromoteSet(scope.row)">修改推广设置</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
    <el-dialog center :visible.sync="qrcode.show" width="fit-content">
      <img :src="qrcode.url" alt="" />
    </el-dialog>
    <!--推广设置已作废 20230926 -->
    <!--    <PromoteSet @cancel="showPromoteSet = false" @confirm="confirmPromotSet"  :type="1" :show="showPromoteSet" :list="promoteList"/>-->

    <el-dialog title="导入小区住户" :visible.sync="importResident.show" width="fit-content" center :close-on-click-modal="false">
      <div style="margin: 50px 100px">
        <el-upload :class="['upload', importResident.file ? '' : 'no-file']" action="#" :auto-upload="false" :on-change="getResidentFile" accept=".xls,.xlsx" :show-file-list="false">
          <i v-if="!importResident.file" class="el-icon-plus"></i>
          <div class="excel-file" v-else>
            <img src="/src/assets/img/excel.png" alt="" />
            <div>
              {{ importResident.file.name }}
            </div>
          </div>
        </el-upload>
        <div style="margin-top: 4px">
          <a style="color: red; text-decoration: none" :href="importResident.importModule"> 下载导入模板 </a>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="confirmImportResident" type="primary">确定</el-button>
        <el-button @click="importResident.show = false">取消</el-button>
      </div>
    </el-dialog>
    <VillageStatistics v-model="statistics.show" :list="statistics.userList" :sumUserNum="statistics.sumUserNum" :villageName="statistics.villageName"></VillageStatistics>

    <ChannelEntrySet :idArr="ids" type="1" @handleClose="channelClose" @handleConfirm="channelConfirm" :channelShow="channelShow"></ChannelEntrySet>
  </div>
</template>
<script>
import VillageApi from '@/api/address/village';
import Region from '@/components/Region';
import VillageStatistics from './components/VillageStatistics.vue';
import * as message from '@/constants/message';
import ChannelEntrySet from '@/components/ChannelEntrySet.vue';
import uploadOssFn from '@/utils/uploadOssFn';
import { VILLAGE_RESIDENT_IMPORT } from '../../constants/constants';

export default {
  name: 'VillageManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    let _this = this;
    return {
      ids: [],
      channelShow: false,
      dataList: [],
      listLoading: true,
      filters: {
        name: '',
        streetIds: [],
        provinceId: '',
        cityId: '',
        areaId: '',
        streetId: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },

      selectedList: [],
      selectedVillageId: '',
      promoteList: [],
      promoteBatch: false,
      showPromoteSet: false,
      promoteType: 1,
      permissionAdd: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_SEE',
      permissionPerfect: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_PERFECT',
      permissionDelete: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_DELETE',
      //permissionPromote:"SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_PROMOTE",
      //permissionBatchPromote:"SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_BATCH_PROMOTE",
      permissionStatisticsUser: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_STATISTICS_USER',
      permissionQrcode: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_QRCODE',
      permissionChannel: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_BATCH_CHANNEL',
      permissionResident: 'SYSTEM_MANAGER_ADDRESS_VILLAGE_LIST_IMPORT_RESIDENT',
      statistics: {
        show: false,
        userList: [],
        sumUserNum: '',
        villageName: '',
      },
      qrcode: {
        show: false,
        url: '',
      },
      importResident: {
        show: false,
        file: '',
        importModule: VILLAGE_RESIDENT_IMPORT,
      },
    };
  },
  components: {
    Region,
    VillageStatistics,
    ChannelEntrySet,
  },

  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    handleClickPerfect(row){
      let _this = this;
      _this.$router.push({
        path: '/address/perfectData',
        query: { id: row.villageId },
      });
    },
    handleImportResident() {
      this.importResident.file = '';
      this.importResident.show = true;
    },
    // 确定导入住户信息
    async confirmImportResident() {
      const { importResident } = this;
      let res = await uploadOssFn([importResident.file], 'importResident');
      await VillageApi.importResidentFile({ url: res[0].url });
      this.$message.success('导入成功');
      importResident.show = false;
    },
    channelClose(e) {
      this.channelShow = e;
    },
    channelConfirm(e) {
      this.channelShow = e;
      this.ids = [];
      this.init();
    },
    handleClickChannel(e) {
      if (e) {
        this.ids = [];
        this.$refs.tableList.clearSelection();
        this.$refs.tableList.toggleRowSelection(e, true);
        if (!this.ids.includes(e.villageId)) {
          this.ids.push(e.villageId);
        }
      }
      if (this.ids.length == 0) {
        this.$message.error('请选择小区');
        return false;
      }
      this.channelShow = true;
    },
    init() {
      let _this = this;
      _this.listLoading = true;
      _this.listData();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    handleSelectChange(val) {
      console.log(val);
      this.selectedList = val;
      this.ids = val.map((item) => item.villageId);
    },
    getResidentFile(val) {
      this.importResident.file = val;
    },
    // 批量推广设置
    /*handleBatchPromoteSet(){
      if(this.selectedList.length==0){
        this.$message.error("请至少选择一项")
        return
      }
      this.promoteList = []
      this.promoteBatch = true
      this.showPromoteSet = true
    },
    // 单个推广设置
    handlePromoteSet(row){
      this.promoteBatch = false
      this.selectedVillageId = row.villageId
      PromoteRuleApi.promoteProfitList({villageId:row.villageId}).then(res=>{
        this.promoteList = res.data
        this.showPromoteSet = true
      })

    },
    confirmPromotSet(){
      let params = {
        list:this.promoteList,
        type:1
      }
      if(this.promoteBatch){
        params.ids = this.selectedList.map(item=>item.villageId)
      }else{
        params.id = this.selectedVillageId
      }
      PromoteRuleApi.setPromoteProfit(params).then(res=>{
        this.$Utils.notifySuccess("设置成功")
        this.showPromoteSet = false
        this.listData()
      })
    },*/
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    // 生成二维码
    async handleGetQrocde(row) {
      const params = {
        id: row.villageId,
        state: 1,
      };
      const loading = this.$loading({
        lock: true,
        text: '生成二维码中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        const { data } = await VillageApi.createWxUrl(params);
        const { qrcode } = this;
        qrcode.show = true;
        qrcode.url = data;
      } catch (err) {}

      loading.close();
    },
    handleClickAdd() {
      let _this = this;
      _this.$router.push('/address/villageAdd');
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: '/address/villageEdit',
        query: { id: row.villageId },
      });
    },
    handleClickDelete(val) {
      let _this = this;
      _this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        VillageApi.deleteVillage({
          id: val.villageId,
          state: -1,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/address/villageDetail',
        query: { id: row.villageId },
      });
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.filters.provinceId = '';
      this.filters.cityId = '';
      this.filters.areaId = '';
      this.filters.streetId = '';
      this.filters.streetIds = [];
      this.onSearch();
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listData();
    },
    handleItemChange(val) {
      this.filters.provinceId = val.provinceId;
      this.filters.cityId = val.cityId;
      this.filters.areaId = val.areaId;
      this.filters.streetId = val.streetId;
      if (val.provinceId) {
        this.filters.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
      } else {
        this.filters.streetIds = [];
      }
    },
    handleClickStatistics(row) {
      VillageApi.statisticsUser({ villageId: row.villageId }).then((res) => {
        const { statistics } = this;
        statistics.show = true;
        statistics.userList = res.data.list;
        statistics.sumUserNum = res.data.sumUserNum;
        statistics.villageName = row.villageName;
      });
    },
    listData() {
      // 获取列表数据
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
      };
      cond.name = _this.filters.name;
      cond.provinceId = _this.filters.provinceId;
      cond.cityId = _this.filters.cityId;
      cond.areaId = _this.filters.areaId;
      cond.streetId = _this.filters.streetId;
      VillageApi.listVillage(cond)
        .then((res) => {
          _this.dataList = res.data.list;
          _this.page.pageTotal = res.data.total;
          _this.listLoading = false;
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>

<style lang="scss" scoped>
.upload {
  .el-icon-plus {
    font-size: 30px;
  }

  .excel-file {
    height: 100px;
    text-align: center;

    img {
      width: 100px;
    }
  }
}

.no-file {
  &::v-deep .el-upload {
    height: 150px;
    width: 150px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    border: 1px rgb(160, 160, 160) dashed;
    border-radius: 4px;

    &:hover {
      border-color: black;
    }
  }
}
</style>
